#include "../xkit.h"

#ifdef XKIT_OS_WINDOWS
    #include <windows.h>
#elif defined(XKIT_OS_LINUX)
    #include <linux/time.h>
#endif

/** losu-capi () -> number
 * @brief: "返回UNIX时间戳，单位为秒，精度随实现而定"
 */
int32_t THISxkit_MODULEchrono_FUNCtimestamp(losu_vm_t vm, int32_t argc, losu_object argv[]) {
    (void)argc;
    (void)argv;
#if defined(XKIT_OS_LINUX)
    struct timespec tp;
    clock_gettime(CLOCK_REALTIME, &tp);
    return arg_returnNum(vm, (double)tp.tv_sec + (double)tp.tv_nsec / 1000000000.0);
#elif defined(XKIT_OS_WINDOWS)
    FILETIME ft;
    GetSystemTimeAsFileTime(&ft);
    
    ULARGE_INTEGER uli;
    uli.LowPart = ft.dwLowDateTime;
    uli.HighPart = ft.dwHighDateTime;
    
    static const uint64_t EPOCH_DIFFERENCE = 116444736000000000ULL;
    double timestamp = (uli.QuadPart - EPOCH_DIFFERENCE) / 10000000.0;
    
    return arg_returnNum(vm, timestamp);
#else
    __error_UnsupportedPlatforms(vm);
    return 0;
#endif
}